<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\RoomFission\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use MoChat\App\WorkContact\Contract\WorkContactRoomContract;
use MoChat\App\WorkRoom\Contract\WorkRoomContract;
use MoChat\App\WorkRoom\Event\DeleteRoomMemberEvent;
use MoChat\Plugin\RoomFission\Contract\RoomFissionContactContract;
use MoChat\Plugin\RoomFission\Contract\RoomFissionContract;
use Psr\Container\ContainerInterface;

/**
 * 客户群变更事件
 * 客户群被修改后（群名变更，群成员增加或移除，群主变更，群公告变更），回调该事件。
 * 收到该事件后，企业需要再调用获取客户群详情接口，以获取最新的群详情。
 *
 * @Listener
 */
class DeleteRoomMemberListener implements ListenerInterface
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @Inject
     * @var WorkRoomContract
     */
    private $workRoomService;

    /**
     * @var WorkContactRoomContract
     */
    private $workContactRoomService;

    /**
     * @var RoomFissionContract
     */
    private $roomFissionService;

    /**
     * @var RoomFissionContactContract
     */
    private $roomFissionContactService;

    public function listen(): array
    {
        return [
            DeleteRoomMemberEvent::class,
        ];
    }

    /**
     * @param DeleteRoomMemberEvent $event
     */
    public function process(object $event)
    {
        try {
            $message = $event->message;
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->workRoomService = $this->container->get(WorkRoomContract::class);
            $this->workContactRoomService = $this->container->get(WorkContactRoomContract::class);
            $this->roomFissionService = $this->container->get(RoomFissionContract::class);
            $this->roomFissionContactService = $this->container->get(RoomFissionContactContract::class);

            $corpId = $message['corpId'];
            $deleteContactRoomIdArr = $message['rooms'];

            foreach ($deleteContactRoomIdArr as $item) {
                $contactRoom = $this->workContactRoomService->getWorkContactRoomById($item, ['unionid', 'room_id']);
                if (empty($contactRoom['unionid'])) {
                    continue;
                }

                $contactRecord = $this->roomFissionContactService->getRoomFissionContactByRoomIdUnionIdFissionID($contactRoom['roomId'], $contactRoom['unionid'], 0, ['id', 'fission_id', 'is_new', 'parent_union_id']);
                if (empty($contactRecord)) {
                    continue;
                }

                $fission = $this->roomFissionService->getRoomFissionById($contactRecord['fissionId'], ['target_count', 'new_friend', 'delete_invalid']);
                if (empty($fission)) {
                    continue;
                }

                // 流失
                $this->roomFissionContactService->updateRoomFissionContactById($contactRecord['id'], ['loss' => 1]);
                // 有师傅并且流失无效
                if (empty($contactRecord['parentUnionId']) && $fission['deleteInvalid'] === 1) {
                    continue;
                }

                $parent = $this->roomFissionContactService->getRoomFissionContactByRoomIdUnionIdFissionID($contactRoom['roomId'], $contactRecord['parentUnionId'], $contactRecord['fissionId'], ['id', 'invite_count', 'status', 'receive_status']);
                $num = $parent['inviteCount'] - 1;
                $status = $parent['status'];
                // 已完成未领取
                if ($parent['status'] === 1 && $parent['receiveStatus'] === 0) {
                    $status = 0;
                }
                $this->roomFissionContactService->updateRoomFissionContactById($parent['id'], ['invite_count' => $num, 'status' => $status]);
            }
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('[群裂变客成员删除事件]监听失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
